﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Mindfor.Web.Models
{
	/// <summary>
	/// Defines properties and methods to create web-link.
	/// </summary>
	public class Link
	{
		/// <summary>
		/// Initializes new instance.
		/// </summary>
		public Link()
		{
			SelectedCssClass = "selected";
		}

		/// <summary>
		/// Initializes new instance.
		/// </summary>
		/// <param name="text">Link text.</param>
		/// <param name="url">Link href.</param>
		public Link(string text, string url)
			: this()
		{
			Text = text;
			Url = url;
		}

		/// <summary>
		/// Gets or sets link text.
		/// </summary>
		public string Text { get; set; }

		/// <summary>
		/// Gets or sets link tooltip.
		/// </summary>
		public string Tooltip { get; set; }

		/// <summary>
		/// Gets or sets navigate URL.
		/// </summary>
		public string Url { get; set; }

		/// <summary>
		/// Gets or sets navigate target.
		/// </summary>
		public string Target { get; set; }

		/// <summary>
		/// Gets or sets wheather link is selected.
		/// If selected then class="selected".
		/// </summary>
		public bool Selected { get; set; }

		/// <summary>
		/// Gets or sets css class that is set when Selected=true.
		/// Default = "selected".
		/// </summary>
		public string SelectedCssClass { get; set; }

		/// <summary>
		/// Gets or sets image url.
		/// </summary>
		public string ImageUrl { get; set; }

		/// <summary>
		/// Gets or sets link additional attributes.
		/// </summary>
		public object Attributes { get; set; }

		public override string ToString()
		{
			return Text;
		}

		/// <summary>
		/// Returns object rendered to tag <a>.
		/// </summary>
		/// <returns>String.</returns>
		public MvcHtmlString ToHtml()
		{
			TagBuilder a = new TagBuilder("a");
			a.InnerHtml = Text;

			// set custom attrs
			if (Attributes != null)
			{
				Dictionary<string, object> dic = new Dictionary<string, object>();
				dic.Add(Attributes);
				a.MergeAttributes(dic, true);
			}

			if (Url != null)
				a.Attributes["href"] = Url.ToString();
			if (!String.IsNullOrEmpty(Tooltip))
				a.Attributes["title"] = Tooltip;
			if (!String.IsNullOrEmpty(Target))
				a.Attributes["target"] = Target;
			if (Selected && !String.IsNullOrEmpty(SelectedCssClass))
				a.AddCssClass(SelectedCssClass);
			
			// render tag
			return new MvcHtmlString(a.ToString());
		}
	}
}
